﻿
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
//using Microsoft.Office.Interop.PowerPoint;

namespace PPTHelper
{
    partial class PPTHelper : IDisposable
    {
        public static string Title { get; set; } = "PPT助手 v1.4";

        //Application app = null;
        //SlideShowWindow show = null;
        dynamic app = null;
        dynamic show = null;
        bool isWpp = false;
        DateTime startTime = DateTime.Now;  //开始时间
        DateTime stopTime = DateTime.Now;   //结束时间
        public TimeSpan Time => stopTime > startTime ? CountdownTime - (stopTime - startTime) : new TimeSpan();
        public TimeSpan CountdownTime { get; set; } = new TimeSpan(); //倒计时
        public string TimeText => $"{Time:h\\:mm\\:ss}";  //前端时间显示样式，不显示符号，实际正计时为负数，倒计时为正数。
        string TempPath { get; set; } = Path.Combine(Path.GetTempPath(), "PPTHelper");  //储存临时图片文件

        public PPTHelper()
        {
            Log.Info("PPTHelper Runing");

            //建立临时文件夹
            if (!Directory.Exists(TempPath)) Directory.CreateDirectory(TempPath);

            //网络服务
            if (NetworkInterface.GetIsNetworkAvailable())
            {
                HttpSvr(); //Http
                WsSvr();   //WebSocket
            }

            //循环检测
            Task.Run(async () =>
             {
                 while (true)
                 {
                     //检查APP对象
                     CheckComObject();
                     //检查计时器
                     CheckTimer();
                     //延时
                     await Task.Delay(500);
                 }
             }).ConfigureAwait(false);

        }

        public void CheckTimer()
        {
            if (app != null && show != null)
            {
                //结束时间
                stopTime = DateTime.Now;
            }
            else
            {
                //开始时间
                startTime = DateTime.Now;
            }
        }

        public void CheckComObject()
        {
            // 尝试获取PowerPoint.Application
            if (app == null)
            {
                try
                {
                    app = Marshal.GetActiveObject("PowerPoint.Application");
                }
                catch (Exception) { }
            }

            // 如果不存在，尝试获取KWPP.Application
            if (app == null)
            {
                try
                {
                    app = Marshal.GetActiveObject("KWPP.Application");
                }
                catch (Exception) { }
            }


            if (app != null)
            {
                //访问app对象 失败释放COM对象
                try
                {
                    isWpp = ((string)(app.Name)).Contains("KWPP");
                    Log.Info(app.Name);
                }
                catch (Exception)
                {
                    try { Marshal.FinalReleaseComObject(app); } catch (Exception) { }
                    app = null;
                    Log.Warn("app Release");
                }

                //访问ShowWindow对象 失败释放COM对象
                try
                {
                    show = app.SlideShowWindows[1];
                    Log.Info("ShowWindows Exist");
                }
                catch (Exception)
                {
                    try { Marshal.FinalReleaseComObject(show); } catch (Exception) { }
                    show = null;
                    Log.Warn("ShowWindows Release");
                }
            }
        }


        #region PPT控制

        //添加事件
        private void AddEvent()
        {
            //不稳定，原因未知
            /*
            app.SlideShowBegin += (Wn) => { show = Wn; };
            app.SlideShowEnd += (Wn) => { show = null; };
            app.SlideShowOnPrevious += (Wn) => { };
            app.SlideShowOnNext += (Wn) => { };
            */
        }

        //获取PPT数据
        public DataInfo GetData()
        {
            var data = new DataInfo { IsWpp = isWpp };
            try
            {
                //活动PPT数据
                if (app != null && !isWpp && app?.Presentations.Count > 0)
                {
                    data.FileName = app.ActivePresentation.Name;
                    data.SlidesCount = app.ActivePresentation.Slides.Count;
                    //放映数据
                    if (show != null)
                    {
                        data.FileName = show.Presentation.Name;
                        data.SlidesCount = show.Presentation.Slides.Count;
                        data.SlideIndex = show.View.CurrentShowPosition;
                        data.ClickCount = show.View.GetClickCount();
                        data.ClickIndex = show.View.GetClickIndex();
                        data.PresentationElapsedTime = (int)show.View.PresentationElapsedTime;
                        data.SlideElapsedTime = (int)show.View.SlideElapsedTime;
                        data.Time = TimeText;
                        data.NotesText = show.View.Slide.NotesPage.Shapes[2].TextFrame.TextRange.Text;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Warn("GetData：" + ex.Message);
            }
            Log.Info($"DataInfo:{data.FileName} {data.SlideIndex}/{data.SlidesCount} {data.Time}");
            return data;
        }

        //获取PPT图片
        public byte[] GetImage(int i)
        {
            var result = Properties.Resources.PPT_jpg;
            try
            {
                if (show != null && i >= 1 && i <= show.Presentation.Slides.Count)
                {
                    var file = $"{show.Presentation.Name}_{i}.png";
                    var filepath = Path.Combine(TempPath, file);
                    var w = (int)(show.Presentation.PageSetup.SlideWidth);
                    var h = (int)(show.Presentation.PageSetup.SlideHeight);
                    if (!File.Exists(filepath)) show.Presentation.Slides[i].Export(filepath, "png", w, h);
                    Log.Info($"GetImage：{filepath}");
                    result = File.ReadAllBytes(filepath);
                }
            }
            catch (Exception ex)
            {
                Log.Warn("GetImage：" + ex.Message);
            }
            Log.Info($"GetImageLength {result.Length}");
            return result;
        }


        //播放
        public void Play()
        {
            show = app?.ActivePresentation.SlideShowSettings.Run();
            Log.Info("Play");
        }

        //停止
        public void Stop()
        {
            show?.View.Exit();
            show = null;
            Log.Info("Stop");
        }

        //上一步
        public void Previous()
        {
            show?.View.Previous();
            Log.Info("Previous");
        }

        //下一步
        public void Next()
        {
            show?.View.Next();
            Log.Info("Next");
        }

        //第一张
        public void First()
        {
            show?.View.First();
            Log.Info("First");
        }

        //最后一张
        public void Last()
        {
            show?.View.Last();
            Log.Info("Last");
        }


        //画线
        public void DrawLine(float BeginX, float BeginY, float EndX, float EndY)
        {
            show?.View.DrawLine(BeginX, BeginY, EndX, EndY);
        }

        #endregion


        public void Dispose()
        {
            //删除临时文件
            try { if (Directory.Exists(TempPath)) Directory.Delete(TempPath, true); } catch (Exception) { }

            //释放对象
            try { Marshal.FinalReleaseComObject(show); } catch (Exception) { }
            try { Marshal.FinalReleaseComObject(app); } catch (Exception) { }
        }

    }
}

